package com.niit.reflect;

import com.niit.entity.Student;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflect {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {

        // 1. 获取Class对象
        Class clazz1 = Class.forName("com.niit.entity.Student");
        Class clazz2 = Student.class;

        // 2.  取全部属性信息
        Field[] fields = clazz1.getDeclaredFields();

        for(Field field : fields){
            System.out.println("Name:"+field.getName()+",Type:"+field.getType());
        }
        // 3. 某个属性赋值
        Object student = clazz1.getDeclaredConstructor().newInstance();

        Field idField = clazz1.getDeclaredField("id");
        idField.setAccessible(true);
        idField.set(student,1001);
        System.out.println("-----------以下是method列表-----");
        // 4. 获取所有方法信息
        Method[] methods = clazz1.getDeclaredMethods();
        for (Method method : methods){
            System.out.println("Name:"+method.getName()+",ReturnType:"+method.getReturnType());

            if(method.getName().equals("sayHello")){
                method.invoke(student);
            }
        }
    }
}
